<?php
require_once '../includes/functions.php';
check_login();

header('Content-Type: application/json');

$template_name = $_POST['template'] ?? '';
$subdomain = $_POST['subdomain'] ?? '';

// 至少需要提供一个参数
if (empty($template_name) && empty($subdomain)) {
    http_response_code(400);
    echo json_encode(['error' => '参数错误：需要提供template或subdomain参数']);
    exit;
}

// 根据参数类型确定资源路径
if (!empty($subdomain)) {
    // 验证子域名格式
    if (!preg_match('/^[a-zA-Z0-9-]+$/', $subdomain)) {
        http_response_code(400);
        echo json_encode(['error' => '无效的子域名']);
        exit;
    }
    
    $base_dir = "../landing_pages/{$subdomain}";
    $resources_dir = "{$base_dir}/resources";
    // 对于落地页，使用相对于落地页根目录的路径
    $url_prefix = "/landing_pages/{$subdomain}/resources/";
    
    // 确保基础目录存在
    if (!file_exists($base_dir)) {
        if (!mkdir($base_dir, 0777, true)) {
            http_response_code(500);
            echo json_encode(['error' => '无法创建上传目录']);
            exit;
        }
    }
} else {
    // 验证模板名称格式
    if (!preg_match('/^[a-zA-Z0-9-_]+$/', $template_name)) {
        http_response_code(400);
        echo json_encode(['error' => '无效的模板名称']);
        exit;
    }
    
    $template_path = get_template_path($template_name);
    $resources_dir = $template_path . '/resources';
    
    // 检查模板是否存在
    if (!file_exists($template_path) || !is_dir($template_path)) {
        http_response_code(404);
        echo json_encode(['error' => '模板不存在']);
        exit;
    }
    
    $url_prefix = "/templates/{$template_name}/resources/";
}

// 确保资源目录存在
if (!file_exists($resources_dir)) {
    if (!mkdir($resources_dir, 0777, true)) {
        http_response_code(500);
        echo json_encode(['error' => '无法创建资源目录']);
        exit;
    }
}

// 处理上传的文件
$uploaded_files = [];
$errors = [];

if (!isset($_FILES['files'])) {
    http_response_code(400);
    echo json_encode(['error' => '没有上传文件']);
    exit;
}

// 获取当前资源列表
$resources_file = $resources_dir . '/resources.json';
$resources = [];
if (file_exists($resources_file)) {
    $resources = json_decode(file_get_contents($resources_file), true) ?? [];
}

// 确保resources是数组
if (!is_array($resources)) {
    $resources = [];
}

foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
    $file_name = $_FILES['files']['name'][$key];
    $file_type = $_FILES['files']['type'][$key];
    $file_size = $_FILES['files']['size'][$key];
    $file_error = $_FILES['files']['error'][$key];

    // 检查文件类型
    if (!preg_match('/^(image|video)\//', $file_type)) {
        $errors[] = "文件 {$file_name} 类型不支持";
        continue;
    }

    // 检查上传错误
    if ($file_error !== UPLOAD_ERR_OK) {
        $errors[] = "文件 {$file_name} 上传失败: " . $file_error;
        continue;
    }

    // 生成唯一文件名
    $extension = pathinfo($file_name, PATHINFO_EXTENSION);
    $new_filename = uniqid() . '.' . $extension;
    $file_path = $resources_dir . '/' . $new_filename;

    // 移动上传的文件
    if (move_uploaded_file($tmp_name, $file_path)) {
        // 设置文件权限
        chmod($file_path, 0644);
        
        // 简化类型为'image'或'video'
        $simple_type = strpos($file_type, 'image/') === 0 ? 'image' : 'video';
        
            $resource_info = [
                'filename' => $new_filename,
                'type' => $simple_type,
                'path' => 'resources/' . $new_filename,
                'description' => $file_name, // 使用原始文件名作为描述
                'url' => $url_prefix . $new_filename
            ];

            // 如果是视频文件，生成封面图
            if ($simple_type === 'video') {
                $thumbnail_filename = 'thumb_' . pathinfo($new_filename, PATHINFO_FILENAME) . '.jpg';
                $thumbnail_path = $resources_dir . '/' . $thumbnail_filename;
                
                // 使用ffmpeg生成封面图
                $ffmpeg_command = "ffmpeg -i \"{$file_path}\" -ss 00:00:01 -vframes 1 -q:v 2 \"{$thumbnail_path}\"";
                exec($ffmpeg_command);
                
                if (file_exists($thumbnail_path)) {
                    $resource_info['thumbnail'] = 'resources/' . $thumbnail_filename;
                }
            }
        
        $resources[] = $resource_info;
        $uploaded_files[] = $resource_info;
    } else {
        $move_error = error_get_last();
        $errors[] = "文件 {$file_name} 保存失败: " . ($move_error ? $move_error['message'] : '未知错误');
    }
}

// 保存更新后的资源信息
if (!empty($uploaded_files)) {
    $json_content = json_encode($resources, JSON_PRETTY_PRINT);
    if ($json_content === false) {
        $json_error = json_last_error_msg();
        http_response_code(500);
        echo json_encode(['error' => "JSON编码失败: {$json_error}"]);
        exit;
    }
    
    if (file_put_contents($resources_file, $json_content) === false) {
        $write_error = error_get_last();
        http_response_code(500);
        echo json_encode(['error' => "保存资源信息失败: " . ($write_error ? $write_error['message'] : '未知错误')]);
        exit;
    }
}

// 返回结果
echo json_encode([
    'success' => true,
    'files' => $uploaded_files,
    'errors' => $errors
]);
